package webtest;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.JFrame;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamMotionDetector;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamResolution;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

public class MotionCapture extends JFrame implements WebcamPanel.Painter {

    private static final long serialVersionUID = 1L;
    private final Webcam webcam;
    private final WebcamPanel panel;
    private final WebcamPanel.Painter painter;
    private final WebcamMotionDetector detector;

    public MotionCapture() {

        //WebcamStreamer stream = new WebcamStreamer(8081, Webcam.getDefault(), 1, true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Motion Detector");
        webcam = Webcam.getDefault();
        webcam.setViewSize(WebcamResolution.VGA.getSize());
        panel = new WebcamPanel(webcam, false);
        painter = panel.getPainter();
        panel.setPainter(this);
        panel.start();
        detector = new WebcamMotionDetector(webcam);
        detector.setInterval(500);
        detector.setPixelThreshold(50);
        detector.start();
        add(panel);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) throws IOException {
        new MotionCapture();
    }

    @Override
    public void paintPanel(WebcamPanel panel, Graphics2D g2) {
        painter.paintPanel(panel, g2);
    }

    @Override
    public void paintImage(WebcamPanel panel, BufferedImage image, Graphics2D g2) {
        double s = detector.getMotionArea();
        Point cog = detector.getMotionCog();
        Graphics2D g = image.createGraphics();
        g.setColor(Color.WHITE);
        g.drawString(String.format("Area: %.2f%%", s), 10, 20);
        if (detector.isMotion()) {
            g.setStroke(new BasicStroke(2));
            g.setColor(Color.RED);
            g.drawOval(cog.x - 5, cog.y - 5, 10, 10);
            for (long stop = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(1); stop > System.nanoTime();) {
                getImage();
            }
        } else {
            g.setColor(Color.GREEN);
            g.drawRect(cog.x - 5, cog.y - 5, 10, 10);
        }
        g.dispose();
        painter.paintImage(panel, image, g2);
    }

    private void getImage() {
        DateFormat dateFormat = new SimpleDateFormat("dd.MM.YYYY");
        Date date = new Date();
        File folder = new File(dateFormat.format(date));
        folder.mkdir();
        File file = new File(String.format("%s/test-%d.jpg", folder, System.currentTimeMillis()));
        try {
            ImageIO.write(webcam.getImage(), "JPG", file);
        } catch (IOException ex) {
            Logger.getLogger(MotionCapture.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Image saved in " + file.getAbsolutePath());
    }

    public byte[] getStream() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        try {
            ImageIO.write(webcam.getImage(), "jpg", bos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return baos.toByteArray();
    }

}
